package com.jasiri.project.ui.process.page

import android.annotation.SuppressLint
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jasiri.project.R
import com.jasiri.project.adapter.OcrTypeAdapter
import com.jasiri.project.databinding.PageOcrBinding
import com.jasiri.project.pro.ProFragment
import com.jasiri.project.utils.DensityUtils
import com.jasiri.project.utils.rv.LinearDecoration
import com.jasiri.lib.baseadapter.JasiriOnItemChildClickListener
import org.json.JSONObject

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/4/19 16:49
 * @Annotation：流程 - 证件照
 */
class OcrPage(): ProFragment() {

    private var _binding: PageOcrBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    //类型列表
    private val typeIconNormalList = arrayListOf(R.mipmap.img_ocr_idcard_normal,R.mipmap.img_ocr_passport_normal,R.mipmap.img_ocr_drving_license_normal,R.mipmap.img_ocr_election_card_normal,R.mipmap.img_ocr_no_documents_normal)
    private val typeIconSelectList = arrayListOf(R.mipmap.img_ocr_idcard_select,R.mipmap.img_ocr_passport_select,R.mipmap.img_ocr_drving_license_select,R.mipmap.img_ocr_election_card_select,R.mipmap.img_ocr_no_documents_select)
    private val typeTitleList = arrayListOf(R.string.process_ocr_idcard,R.string.process_ocr_passport,R.string.process_ocr_drving_license,R.string.process_ocr_election_card,R.string.process_ocr_no_documents)

    //身份验证类型
    private var mTypeAdapter: OcrTypeAdapter? = null

    //是否选中删除信息,默认选中
    private var isSelectedDelete = true

    private var stepItem: JSONObject? = null
    constructor(data: JSONObject): this(){
        this.stepItem = data
    }

    override fun getRootView(inflater: LayoutInflater): View {
        _binding = PageOcrBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#FFF8F8F8"))
        isSelectedDelete = true
        showSelectedDeleteViewTips()
        initRecyclerView()
    }

    override fun initListener() {
        //切换是否选中删除个人信息
        _binding?.imgSelected?.setOnClickListener {
            isSelectedDelete = !isSelectedDelete
            showSelectedDeleteViewTips()
        }
    }

    override fun initData() {
        var ocrTypeSize = typeTitleList.size
        //从配置中获取是否支持不传证件照
        val commonData = getCommonObject()
        val customize = commonData.optJSONObject("customize")
        customize?.let {
            val customData = customize.optJSONObject("customData")
            if (customData != null){
                //是否支持选择不传证件照
                val isNoDocuments = customData.optString("ocrNoDocuments")
                if (isNoDocuments != "YES"){
                    ocrTypeSize -= 1
                }
            }
        }

        val typeList = arrayListOf<JSONObject>()
        for (i in 0..< ocrTypeSize){
            val obj = JSONObject()
            obj.put("isSelect",i == 0)
            obj.put("normalIconId",typeIconNormalList[i])
            obj.put("selectIconId",typeIconSelectList[i])
            obj.put("title",requireContext().getString(typeTitleList[i]))
            typeList.add(obj)
        }
        mTypeAdapter?.data = typeList
        showContentView(0)
    }

    /**
     * 初始化绑卡列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun initRecyclerView() {
        _binding?.rvType?.setHasFixedSize(true)
        _binding?.rvType?.isNestedScrollingEnabled = false
        _binding?.rvType?.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        _binding?.rvType?.layoutManager = layoutManager
        mTypeAdapter = OcrTypeAdapter(_binding?.rvType)
        val topDecoration = DensityUtils.dp2px(12f)
        _binding?.rvType?.addItemDecoration(LinearDecoration(0, topDecoration, 0, 0))
        _binding?.rvType?.adapter = mTypeAdapter
        _binding?.rvType?.itemAnimator = DefaultItemAnimator()
        mTypeAdapter?.setOnItemChildClickListener(JasiriOnItemChildClickListener { _, childView, position ->
            if (childView.id == R.id.itemLayout) {
                mTypeAdapter?.let {
                    for (i in 0..<it.itemCount) {
                        val item = it.getItem(i)
                        if (i == position) {
                            item.put("isSelect", true)
                        } else {
                            item.put("isSelect", false)
                        }
                    }
                    it.notifyDataSetChanged()
                    showContentView(position)
                }
            }
        })
    }

    private fun showSelectedDeleteViewTips(){
        when(isSelectedDelete){
            true -> {
                _binding?.imgSelected?.setImageResource(R.mipmap.img_orange_selected)
            }
            else -> {
                _binding?.imgSelected?.setImageResource(R.mipmap.img_orange_normal)
            }
        }
    }

    /**
     * 切换类型，显示内容
     */
    private fun showContentView(index: Int){
        //删除提示
        _binding?.deleteTipsLayout?.visibility = View.VISIBLE
        when(index){
            0 -> {//身份证信息
                childFragmentManager
                    .beginTransaction()
                    .replace(R.id.contentLayout, OcrIDCardPage()) // 此处的R.id.fragment_container是要盛放fragment的父容器
                    .commitAllowingStateLoss()
            }
            1 -> {//护照信息
                childFragmentManager
                    .beginTransaction()
                    .replace(R.id.contentLayout, OcrPassportPage()) // 此处的R.id.fragment_container是要盛放fragment的父容器
                    .commitAllowingStateLoss()
            }
            2 -> {//驾驶证信息
                childFragmentManager
                    .beginTransaction()
                    .replace(R.id.contentLayout, OcrDriverLicensePage()) // 此处的R.id.fragment_container是要盛放fragment的父容器
                    .commitAllowingStateLoss()
            }
            3 -> {//选举卡
                childFragmentManager
                    .beginTransaction()
                    .replace(R.id.contentLayout, OcrElectionCardPage()) // 此处的R.id.fragment_container是要盛放fragment的父容器
                    .commitAllowingStateLoss()
            }
            else -> {//
                _binding?.deleteTipsLayout?.visibility = View.GONE
                childFragmentManager
                    .beginTransaction()
                    .replace(R.id.contentLayout, OcrNoDocumentsPage(stepItem)) // 此处的R.id.fragment_container是要盛放fragment的父容器
                    .commitAllowingStateLoss()
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}